﻿namespace GmailReader
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Xml;
    using System.Text.RegularExpressions;

    public class AccountReader
    {
        private IFeedDownloader Downloader { get; set; }

        public AccountReader(string username, string password)
            : this(new FeedDownloader(username, password))
        {
        }

        public AccountReader(IFeedDownloader downloader)
        {
            this.Downloader = downloader;
        }

        public IList<Email> GetUnreadedMails()
        {
            IList<Email> emailCollection = new List<Email>();

            string feed = this.Downloader.Download();
            feed = Regex.Replace(feed, @"<feed.*[""| ]>", "<feed>");

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(feed);

            var mailCount = Convert.ToInt32(xmlDoc.SelectSingleNode("/feed/fullcount").InnerText);
            if (mailCount > 0)
            {
                XmlNodeList nodelist = xmlDoc.SelectNodes("/feed/entry");

                foreach (XmlNode node in nodelist)
                {
                    emailCollection.Add(new Email
                    {
                        Id = node.SelectSingleNode("id").InnerText,
                        Title = node.SelectSingleNode("title").InnerText,
                        Summanry = node.SelectSingleNode("summary").InnerText,
                        Date = node.SelectSingleNode("issued").InnerText,
                        From = FormatFrom(node.SelectSingleNode("author").SelectSingleNode("name").InnerText,
                                          node.SelectSingleNode("author").SelectSingleNode("email").InnerText)
                    });
                }
            }

            return emailCollection;
        }

        private string FormatFrom(string name, string email)
        {
            return string.Format("From: {0}<{1}>", name, email);
        }
    }
}
